using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using GameView.Comment;
using GameView.Services;
using GameView.Services.Comment;
using GameView.Services.Dtos.Project;
using GameView.Views;
using IPPMS.Application.Dtos.CommandRecordDto;
using IPPMS.Application.Dtos.Recharge;
using System.Collections.ObjectModel;
using System.Windows.Controls;

namespace GameView.ViewModels
{
    public partial class CommandRecordViewModel : ObservableValidator
    {
        private List<ProjectWithGamesInfo> pgs = [];
        private readonly ProjectService _proService;
        private readonly CommandRecordService _commandRecordService;

        public CommandRecordViewModel(CommandRecordService crs, ProjectService proService)
        {
            _proService = proService;
            _commandRecordService = crs;
            IsMerchant = StaticValues.LoginInfo.PersonInfo.RoleId != 3;
            LoadData().ConfigureAwait(false);
        }

        [ObservableProperty]
        private bool _isLoading = false;

        [ObservableProperty]
        private int _pageIndex = 1;

        [ObservableProperty]
        private int _pageSize = 50;

        [ObservableProperty]
        private int _totalCount = 0;

        [ObservableProperty]
        private int _totalPages = 1;

        [ObservableProperty]
        private bool _hasPrevPages = false;

        [ObservableProperty]
        private bool _hasNextPages = true;

        [ObservableProperty]
        private ObservableCollection<CommandRecordOutPutDto> _commandRecords;

        [ObservableProperty]
        private int _pageNumber = 1;

        [ObservableProperty]
        private CommandRecordQueryDto _queryDto = new();

        [ObservableProperty]
        private ObservableCollection<string> _projectOptions = [];

        [ObservableProperty]
        [NotifyPropertyChangedFor(nameof(GameOptions))]
        private string _selectedProject;

        [ObservableProperty]
        private ObservableCollection<string> _gameOptions = [];

        [ObservableProperty]
        private bool _isMerchant = true;

        #region st

        [ObservableProperty]
        private long _sTAll = 0;

        [ObservableProperty]
        private long _sT24 = 0;

        [ObservableProperty]
        private long _sTToDay = 0;

        [ObservableProperty]
        private long _sTPage = 0;

        [ObservableProperty]
        private string _sTString = "";

        #endregion st

        [RelayCommand]
        private async Task AddNewAsync()
        {
            await ExtentHelper.GetService<IDialogService>()
          .ShowDialog<CommandRecordAddView>();
            await LoadData();
        }

        [RelayCommand]
        private async Task ConfigAsync()
        {
            await ExtentHelper.GetService<IDialogService>()
          .ShowDialog<CommandAddView>();
            await LoadData();
        }

        [RelayCommand]
        private async Task FirstPage()
        {
            PageIndex = 1;
            PageNumber = 1;
            await LoadData();
        }

        [RelayCommand]
        private async Task PreviousPageAsync()
        {
            PageIndex--;
            PageNumber--;
            await LoadData();
        }

        [RelayCommand]
        private async Task NextPageAsync()
        {
            PageIndex++;
            PageNumber++;
            await LoadData();
        }

        [RelayCommand]
        private void LastPage() => PageIndex = TotalPages;

        [RelayCommand]
        private async Task ChangePageSize(object size)
        {
            ComboBoxItem cb = (ComboBoxItem)size;
            //PageSize = 20;
            if (cb.Content is string sizeStr && int.TryParse(sizeStr.Replace("条/页", ""), out var newSize))
            {
                PageSize = newSize;
                PageIndex = 1; // 重置到第一页
                await LoadData();
            }
        }

        [RelayCommand]
        private async Task SearchAsync()
        {
            IsLoading = true;
            await Task.Delay(200);
            try
            {
                PageIndex = 1;
                await LoadFromApi();
            }
            catch (Exception ex)
            {
                GlobalMessage.Instance.ShowError($"数据加载错误：{ex.Message}");
            }
            finally
            { IsLoading = false; }
        }

          partial void OnSelectedProjectChanged(string value)
        {
            // 清空游戏选项
            GameOptions.Clear();
            // 根据选择的项目重新加载游戏选项
            if (!string.IsNullOrEmpty(value))
            {
                var nowProjet = pgs.FirstOrDefault(q => q.Name == SelectedProject);
                if (nowProjet == null || nowProjet.Games.IsNullOrEmpty())
                    return;
                foreach (var game in nowProjet.Games)
                {
                    GameOptions.Add(game.Name);
                }
            }
        }

        [RelayCommand]
        private async Task LoadData()
        {
            IsLoading = true;
            await Task.Delay(200);
            try
            {
                await LoadFromApi();

                var res = await _proService.GetAllAsync();
                pgs = res.Data;
                ProjectOptions.Clear();
                GameOptions.Clear();
                pgs ??= [];
                foreach (var data in pgs)
                {
                    ProjectOptions.Add(data.Name);
                }
                if (pgs.Count >= 1)
                {
                    foreach (var item in pgs.First().Games)
                        GameOptions.Add(item.Name);
                }
            }
            catch (Exception ex)
            {
                GlobalMessage.Instance.ShowError($"数据加载错误：{ex.Message}");
            }
            finally
            { IsLoading = false; }
        }

        private async Task LoadFromApi()
        {
            QueryDto.PageIndex = PageIndex;
            QueryDto.PageSize = PageSize;
            QueryDto.ProjectName = SelectedProject;

            var res = await _commandRecordService.GetByPage(QueryDto);
            if (res == null)
                return;
            if (res.StatusCode != 200)
            {
                GlobalMessage.Instance.ShowError(JSON.Serialize(res.Errors));
                return;
            }
            TotalPages = res.Data.TotalPages;
            TotalCount = res.Data.TotalCount;
            HasNextPages = res.Data.HasNextPages;
            HasPrevPages = res.Data.HasPrevPages;
            PageIndex = res.Data.PageIndex;
            res.Data.Items ??= [];
            CommandRecords = new(res.Data.Items);
        }
    }
}